package com.flushbonading.controller;


import cn.hutool.core.lang.Validator;
import com.alibaba.druid.util.StringUtils;
import com.auth0.jwt.JWT;
import com.flushbonading.annotation.BackStage;
import com.flushbonading.annotation.StudentNumber;
import com.flushbonading.exception.MyException;
import com.flushbonading.pojo.RespBean;
import com.flushbonading.pojo.dto.ScoreDTO;
import com.flushbonading.pojo.dto.ScoreMessageDTO;
import com.flushbonading.service.IScoreService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zlx&zyx
 * @since 2021-04-07
 */
@RestController
@RequestMapping("/score")
@BackStage
public class ScoreController {
    @Autowired
    private IScoreService scoreService;
    /**
     * 通过课程号得到该课程下学生的成绩相关信息
     * 通过post请求方式
     * 接口请求地址:127.0.0.1:8088/score/select/{course_id}
     *
     * @param course_id 课程号
     * @return <code>List<ScoreDTO></code> 返回学生成绩信息
     */
    @PostMapping("/select/{course_id}")
    public List<ScoreDTO> getSocresByCourseID(@PathVariable("course_id") int course_id){
        /**调用service层的getSocresByCourseID方法**/
        return scoreService.getSocresByCourseID(course_id);
    }
    /**
     * 提交卷面分和总成绩的接口
     * 通过post进行请求
     * 请求地址:127.0.0.1:8088/score/submit/{course_id}
     *
     * @param course_id 从url中获取的课程id
     * @param scoreDTOList 从前端携带进后端的成绩信息数据
     * @return 返回消息对象，用来提示用户是否提交成功
     * */
    @PostMapping("/submit/{course_id}")
    public RespBean insertGrade(@PathVariable("course_id") int course_id,@RequestBody List<ScoreDTO> scoreDTOList){
        //插入每一条从前端传来的成绩信息
        for(ScoreDTO scoreDTO:scoreDTOList)
            scoreService.updateCourses(course_id,scoreDTO);
        //自动计算总分
        scoreService.updateAllScore();
        return RespBean.success("提交成功");
    }

    @PostMapping("/edit/{course_id}")
    public RespBean updateTotalScore(@PathVariable("course_id") int course_id,@RequestBody ScoreDTO scoreDTO) throws MyException {
        if (scoreDTO.getTotal_score().toString().length()>4&&scoreDTO.getTotal_score()>100)
                throw new MyException("您输入的成绩不合法");
        int i = scoreService.updateTotalScore(course_id, scoreDTO);
        if (i>0)
            return RespBean.success("修改成功");
        return RespBean.error("修改失败");
    }

    @PostMapping("/delete/{course_id}/{student_number}")
    public RespBean deleteAScore(@PathVariable("course_id") int course_id,@PathVariable("student_number") String student_number){
        int i = scoreService.deleteAScore(course_id, student_number);
        if (i>0)
           return RespBean.success("删除成功");
        return RespBean.error("删除失败");
    }
    @PostMapping("/search/{course_id}/{student_number}/{name}")
    public List<ScoreDTO> searchScore(@PathVariable("course_id") int course_id, @PathVariable("student_number") String student_number, @PathVariable("name") String name) throws MyException {
        if (student_number.equals("@"))
            student_number="";
        if (name.equals("@"))
            name="";
        if (!student_number.equals("")&&(student_number.length()>11||!StringUtils.isNumber(student_number)))
            throw new MyException("您输入的学号不合法");
        if (!name.equals(""))
            Validator.validateChinese(name,"您输入的姓名不是中文");
        System.out.println(name);
        return scoreService.searchScore(course_id, student_number, name);
    }

    @PostMapping("/selectStudentScores")
    public List<ScoreMessageDTO> getScoresByStudentNumber(HttpServletRequest request){
        String token = request.getHeader("token");
        String user_id = JWT.decode(token).getAudience().get(0);
        return scoreService.getScoresByStudentNumber(user_id);
    }

}
